package com.qf.business.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.business.dao.ICourseDao;
import com.qf.business.entity.Course;
import com.qf.business.entity.CourseSelector;
import com.qf.business.service.CourseSelectorService;
import com.qf.business.service.ICourseSevice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * description:
 * author: Ken
 * 公众号：Java架构栈
 */
@Service
public class CourseServiceImpl extends ServiceImpl<ICourseDao, Course> implements ICourseSevice {

    @Autowired
    private CourseSelectorService courseSelectorService;

    @Autowired
    private ICourseDao courseDao;

    /**
     *
     * 选课的业务
     * @param cid
     * @param sid
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int selectCourse(Integer cid, Integer sid) {

        //判断当前是否已经选过这门课
        Long count = courseSelectorService.query()
                .eq("cid", cid)
                .eq("sid", sid)
                .count();

        if (count > 0) {
            //已经存在
            return -2;
        }

        //将课程id锁住 - 如果不同的学生选择不同的课
        synchronized ((cid + "").intern()) {
            //通过课程id 查询课程剩余座位
            Course course = super.getById(cid);
            if (course.getHasNumber() < 1) {
                //没有座位
                return -1;
            }

            //如果座位足够 - 座位--
//            course.setHasNumber(course.getHasNumber() - 1);
//            boolean flag = super.updateById(course);
            int flag = courseDao.decrNumber(cid, 1);

            //生成学生 - 课程的中间表记录
            if (flag > 0) {
                //添加中间表
                CourseSelector courseSelector = new CourseSelector()
                        .setSid(sid)
                        .setCid(cid);

                //保存记录
                courseSelectorService.save(courseSelector);
            } else {
                throw new RuntimeException("课程修改失败");
            }
        }

        return 1;
    }
}
